package com.hmys.api.controller;

import com.github.pagehelper.PageInfo;
import com.hmys.api.model.*;
import com.hmys.api.response.Result;
import com.hmys.api.response.ResultCode;
import com.hmys.api.response.ResultPage;
import com.hmys.api.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by chen365 on 2018/03/27.
 */
@RestController
@Api(tags = "房产")
@RequestMapping(value = "/house")
public class HouseController {

    @Autowired
    private WebHouseTypeService webHouseTypeService;
    @Autowired
    private WebHouseInvestmentTypeService webHouseInvestmentTypeService;
    @Autowired
    private WebHousePriceSectionService webHousePriceSectionService;
    @Autowired
    private WebHouseProjectTypeService webHouseProjectTypeService;
    @Autowired
    private WebHousePhotoService webHousePhotoService;

    @Autowired
    private WebHouseService webHouseService;

    @ApiOperation(value = "房屋户型", notes = "房屋户型", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @GetMapping(value = "/type")
    public Object type() {
        List<WebHouseType> list = webHouseTypeService.selectAll();
        if (list.size() > 0) {
            return new Result<>(ResultCode.SUCCESS, list);
        } else {
            return new Result<>(ResultCode.NOT_FOUND);
        }
    }

    @ApiOperation(value = "投资类型", notes = "投资类型", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @GetMapping(value = "/investment/type")
    public Object investmentType() {
        List<WebHouseInvestmentType> list = webHouseInvestmentTypeService.selectAll();
        if (list.size() > 0) {
            return new Result<>(ResultCode.SUCCESS, list);
        } else {
            return new Result<>(ResultCode.NOT_FOUND);
        }
    }

    @ApiOperation(value = "价格段位", notes = "价格段位", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @GetMapping(value = "/price/section")
    public Object priceSection() {
        List<WebHousePriceSection> list = webHousePriceSectionService.selectAll();
        if (list.size() > 0) {
            return new Result<>(ResultCode.SUCCESS, list);
        } else {
            return new Result<>(ResultCode.NOT_FOUND);
        }
    }

    @ApiOperation(value = "项目类型", notes = "项目类型", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @GetMapping(value = "/project/type")
    public Object projectType() {
        List<WebHouseProjectType> list = webHouseProjectTypeService.selectAll();
        if (list.size() > 0) {
            return new Result<>(ResultCode.SUCCESS, list);
        } else {
            return new Result<>(ResultCode.NOT_FOUND);
        }
    }


    @ApiOperation(value = "搜索", notes = "搜索", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "int", name = "pageIndex", defaultValue = "1", value = "页码", required = true, paramType = "path"),
            @ApiImplicitParam(dataType = "int", name = "pageSize", defaultValue = "10", value = "每页数", required = true, paramType = "path"),
            @ApiImplicitParam(dataType = "Long", name = "countryId", value = "国家ID", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "Long", name = "sid", value = "州Id", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "Long", name = "cid", value = "城市Id", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "Long", name = "iid", value = "投资类型ID", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "Long", name = "hid", value = "房屋户型ID", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "Long", name = "pid", value = "价格段位ID", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "keyword", value = "搜索关键字", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "filed", value = "排序字段(area:面积，price:价格,time:创建时间,sort:自定义)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "direction", value = "排序方向（asc 升序，desc 降序）", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "Boolean", name = "isRecommend", value = "是否为推荐", required = false, paramType = "query")
    })
    @GetMapping(value = "/search/{pageIndex}/{pageSize}")
    public Object search(@PathVariable("pageIndex") Integer pageIndex,
                         @PathVariable("pageSize") Integer pageSize,
                         Long sid, Long cid, Long iid, Long hid, Long pid, String keyword, String filed, String direction,
                         Boolean isRecommend,@RequestParam(value = "countryId", required = false, defaultValue = "1") Long countryId) {
        WebHouseParam record = new WebHouseParam();

        record.setCountryId(countryId);

        if (!StringUtils.isEmpty(sid)) {
            record.setStateId(sid);
        }
        if (!StringUtils.isEmpty(cid)) {
            record.setCityId(cid);
        }
        if (!StringUtils.isEmpty(iid)) {
            record.setInvestmentTypeId(iid);
        }
        if (!StringUtils.isEmpty(hid)) {
            record.setHouseTypeId(hid);
        }
        if (!StringUtils.isEmpty(pid)) {
            record.setPriceSectionId(pid);
        }
        if (!StringUtils.isEmpty(keyword)) {
            record.setAddress(keyword);
        }
        if (!StringUtils.isEmpty(isRecommend)) {
            record.setIsRecommend(isRecommend);
        }

        if (!StringUtils.isEmpty(filed) && !StringUtils.isEmpty(direction)) {

            if (direction.toLowerCase().equals("asc") || direction.toLowerCase().equals("desc")) {
                if (filed.toLowerCase().equals("area")) {
                    filed = "area";
                }
                if (filed.toLowerCase().equals("price")) {
                    filed = "price";
                }
                if (filed.toLowerCase().equals("time")) {
                    filed = "create_time";
                }
                String orderBy = filed + " " + direction;
                record.setOrderBy(orderBy);
            }
        }

        PageInfo<WebHouse> pageInfo = webHouseService.selectByBean(pageIndex, pageSize, record);
        if (pageInfo.getList().size() > 0) {
            return new ResultPage(ResultCode.SUCCESS, pageInfo);
        } else {
            return new Result<>(ResultCode.NOT_FOUND);
        }
    }

    @ApiOperation(value = "多条件搜索", notes = "多条件搜索", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "int", name = "pageIndex", defaultValue = "1", value = "页码", required = true, paramType = "path"),
            @ApiImplicitParam(dataType = "int", name = "pageSize", defaultValue = "10", value = "每页数", required = true, paramType = "path"),
            @ApiImplicitParam(dataType = "Long", name = "countryId", value = "国家ID", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "sid", value = "州Id(多个以“,”分隔开)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "cid", value = "城市Id(多个以“,”分隔开)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "iid", value = "投资类型ID(多个以“,”分隔开)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "hid", value = "房屋户型ID(多个以“,”分隔开)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "pid", value = "价格段位ID(多个以“,”分隔开)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "keyword", value = "搜索关键字", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "filed", value = "排序字段(area:面积，price:价格,time:创建时间,sort:自定义)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "direction", value = "排序方向（asc 升序，desc 降序）", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "Boolean", name = "isRecommend", value = "是否为推荐", required = false, paramType = "query")
    })
    @GetMapping(value = "/multiple/search/{pageIndex}/{pageSize}")
    public Object multipleSearch(@PathVariable("pageIndex") Integer pageIndex,
                                 @PathVariable("pageSize") Integer pageSize,
                                 String sid, String cid, String iid, String hid, String pid,
                                 String keyword, String filed, String direction, Boolean isRecommend,
                                 @RequestParam(value = "countryId", required = false, defaultValue = "1") Long countryId) {
        WebHouseParamMultiple record = new WebHouseParamMultiple();
        record.setCountryId(countryId);
        //州Id
        if (!StringUtils.isEmpty(sid)) {
            List<Long> sids = Arrays.asList(sid.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
            record.setStateId(sids);
        }
        //城市Id
        if (!StringUtils.isEmpty(cid)) {
            List<Long> cids = Arrays.asList(cid.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
            record.setCityId(cids);
        }
        //投资类型ID
        if (!StringUtils.isEmpty(iid)) {
            List<Long> iids = Arrays.asList(iid.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
            record.setInvestmentTypeId(iids);
        }
        //房屋户型ID
        if (!StringUtils.isEmpty(hid)) {
            List<Long> hids = Arrays.asList(hid.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
            record.setHouseTypeId(hids);
        }
        //价格段位ID
        if (!StringUtils.isEmpty(pid)) {
            List<Long> pids = Arrays.asList(pid.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
            record.setPriceSectionId(pids);
        }
        if (!StringUtils.isEmpty(keyword)) {
            record.setAddress(keyword);
        }
        if (!StringUtils.isEmpty(isRecommend)) {
            record.setIsRecommend(isRecommend);
        }

        if (!StringUtils.isEmpty(filed) && !StringUtils.isEmpty(direction)) {
            if (direction.toLowerCase().equals("asc") || direction.toLowerCase().equals("desc")) {
                if (filed.toLowerCase().equals("area")) {
                    filed = "area";
                }
                if (filed.toLowerCase().equals("price")) {
                    filed = "price";
                }
                if (filed.toLowerCase().equals("time")) {
                    filed = "create_time";
                }
                String orderBy = filed + " " + direction;
                record.setOrderBy(orderBy);
            }
        }

        PageInfo<WebHouse> pageInfo = webHouseService.selectByBean(pageIndex, pageSize, record);
        if (pageInfo.getList().size() > 0) {
            return new ResultPage(ResultCode.SUCCESS, pageInfo);
        } else {
            return new Result<>(ResultCode.NOT_FOUND);
        }
    }

    @ApiOperation(value = "房源图片", notes = "房源图片", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Long", name = "houseId", value = "房源id", required = true, paramType = "path")
    })
    @GetMapping(value = "/photo/{houseId}")
    public Object photo(@PathVariable("houseId") Long houseId) {
        List<String> list = webHousePhotoService.selectPhotoByHouseId(houseId);
        if (list.size() > 0) {
            return new Result<>(ResultCode.SUCCESS, list);
        } else {
            return new Result<>(ResultCode.NOT_FOUND);
        }
    }

    @ApiOperation(value = "房源详情", notes = "房源详情", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Long", name = "houseId", value = "房源id", required = true, paramType = "path")
    })
    @GetMapping(value = "/detail/{houseId}")
    public Object detail(@PathVariable("houseId") Long houseId) {
        WebHouseWithBLOBs record = webHouseService.selectByPrimaryKey(houseId);
        if (record != null) {
            return new Result<>(ResultCode.SUCCESS, record);
        } else {
            return new Result<>(ResultCode.NOT_FOUND);
        }
    }

    @ApiOperation(value = "房源对比", notes = "房源对比", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "ids", value = "多个房源id以','分隔", required = true, paramType = "query")
    })
    @GetMapping(value = "/comparison")
    public Object comparison(String ids) {
        if (StringUtils.isEmpty(ids)) {
            return new Result<>(ResultCode.ERROR_PARAM);
        }

        List<Long> houseIds = Arrays.asList(ids.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        if (houseIds == null || houseIds.size() == 0) {
            return new Result<>(ResultCode.ERROR_PARAM);
        }

        List<WebHouseWithBLOBs> list = webHouseService.selectByIds(houseIds);
        if (list.size() > 0) {
            return new Result<>(ResultCode.SUCCESS, list);
        } else {
            return new Result<>(ResultCode.NOT_FOUND);
        }
    }

}
